package scrum.xmlDatabase;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import scrum.entity.*;

public class ProjectXMLConnector {
	
	public ArrayList<Project> projectList = new ArrayList<Project>();
	
	private String ProjectList_XML = "./project.xml";
	
	// create bookstore, assigning book
	ProjectsStore projectstore = new ProjectsStore();
	
	public ProjectXMLConnector(){
		
		projectstore.setProjectList(projectList);
	}
	
	
	void addProject(Project project){
		projectList.add(project);
	}
	
	public void setProjectList(ArrayList<Project> projectList){
		
		this.projectList = projectList;
		projectstore.setProjectList(projectList);
	}

	
	public void setProjectList_XML(String location){
		
		this.ProjectList_XML = location;
	}

	public void writeToXML()throws JAXBException, IOException{
		
		//if (!projectList.isEmpty()) {
			
			JAXBContext context = JAXBContext.newInstance(ProjectsStore.class);
			Marshaller m = context.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			m.marshal(projectstore, System.out);

			Writer w = null;
			try {
				w = new FileWriter(ProjectList_XML);
				m.marshal(projectstore, w);
			} finally {
				try {
					w.close();
				} catch (Exception e) {
				}
			}
		//}
	}
	
	public ProjectsStore readFromXML()throws JAXBException, IOException{
		
		JAXBContext context = JAXBContext.newInstance(ProjectsStore.class);
		Unmarshaller um = context.createUnmarshaller();
		ProjectsStore projectStore = (ProjectsStore) um.unmarshal(new FileReader(
				ProjectList_XML));
		return projectStore;
	}

}